package com.aircms.service.impl;

import com.aircms.common.Common;
import com.aircms.common.ServerResponse;
import com.aircms.dao.UserRoleMapper;
import com.aircms.dao.UsersMapper;
import com.aircms.pojo.UserRole;
import com.aircms.pojo.Users;
import com.aircms.pojo.validation.BaseQueryFieldsValidation;
import com.aircms.pojo.vo.UserRoleVo;
import com.aircms.service.IUsersService;
import com.aircms.util.JwtUtil;
import com.aircms.util.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "iUsersService")
public class UserServiceImpl implements IUsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserRole userRole;

    @Autowired
    private Users users;

    /**
     * 获取所有用户
     * @return
     */
    public ServerResponse index(BaseQueryFieldsValidation baseQueryFields,int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Users> users=usersMapper.selectAll(baseQueryFields);
        PageInfo pageResult=new PageInfo(users);
        return ServerResponse.resResponse(pageResult);
    }

    /**
     * 用户的登录，返回token
     * @param name
     * @param password
     * @return
     */
    public ServerResponse login(String name,String password){
        password=MD5Util.MD5Encode(password);
        Users users=usersMapper.selectByNameAndPassword(name,password);
        if(users==null){
            return ServerResponse.resResponse("",-102);  // 用户名或密码错误
        }

        // 登录成功生成token
        Map map=new HashMap();
        map.put("id",users.getId());
        map.put("name",users.getName());
        map.put("nickname",users.getNickname());

        // 获取用户角色
        List<UserRole> userRole=userRoleMapper.selectUserRole(users.getId());
        StringBuilder stringBuilder=new StringBuilder();
        if(!userRole.isEmpty()){
            userRole.forEach(item->{
                stringBuilder.append(item.getRoleId());
                stringBuilder.append(",");
            });
            stringBuilder.deleteCharAt(stringBuilder.length()-1);  // 去除尾部“,"
        }

        map.put("role_ids",stringBuilder);

        String token=JwtUtil.createJwt(map,MD5Util.MD5Encode(Common.getIp()+Common.getUserAgent()));  // ip和客户端浏览器认证
        Map resToken=new HashMap();
        resToken.put("token_type","Bearer");
        resToken.put("token",token);
        resToken.put("expires_in",JwtUtil.getExpiresIn());
        return ServerResponse.resResponse(resToken);
    }

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    public ServerResponse show(Integer id){
        Users users= usersMapper.selectByPrimaryKey(id);
        if(users!=null){
            return  ServerResponse.resResponse(users);
        }else {
            return ServerResponse.resResponse("",-900);  // 查无数据
        }
    }

    /**
     * 获取用户角色信息
     * @param userId
     * @return
     */
    public ServerResponse getUserRoles(Integer userId){
        UserRoleVo userRoleVo=usersMapper.selectUserRoles(userId);
        return ServerResponse.resResponse(userRoleVo);
    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    public ServerResponse destroy(Integer id){
        if(usersMapper.setStatus(id,-1)>0){
            return ServerResponse.resResponse();
        }else {
            return ServerResponse.resResponse("",-2,"id 不存在");
        }
    }

    /**
     * 添加用户
     * @param users
     * @return
     */
    public ServerResponse store(Users users){
        if(usersMapper.checkNameExist(users.getName())>0){ // 检测用户名是否存在
            return ServerResponse.resResponse("",-2,users.getName()+"已存在");
        }
        users.setPassword(MD5Util.MD5Encode(users.getPassword()));
        int count=usersMapper.insertSelective(users);
        if(count<1){
            return ServerResponse.resResponse("",-1);
        }
        return ServerResponse.resResponse();
    }


    /**
     * 跟新用户信息
     * @param users
     * @return
     */
    public ServerResponse update(Users users){
        if(usersMapper.checkNameExistExceptId(users.getName(),users.getId())>0){ // 该用户名已经存在
            return ServerResponse.resResponse("",-2,"用户名已经存在");
        }
        if(usersMapper.updateByPrimaryKeySelective(users)<1){
            return ServerResponse.resResponse("",-2,"id不存在");
        }
        return ServerResponse.resResponse();
    }


    /**
     * 跟新用户信息，包括角色信息
     * @param userRoleVo
     * @return
     */
    public ServerResponse updateUserAndUserRole(UserRoleVo userRoleVo){
        if(usersMapper.checkNameExistExceptId(userRoleVo.getName(),userRoleVo.getId())>0){ // 该用户名已经存在
            return ServerResponse.resResponse("",-2,"用户名已经存在");
        }
        if(usersMapper.updateByPrimaryKeySelective(userRoleVo)<1){
            return ServerResponse.resResponse("",-2,"id不存在");
        }
        // 先删除用户所有角色
        userRoleMapper.deleteByUserId(userRoleVo.getId());
        if(userRoleVo.getRoleIds()!=null){
            Arrays.stream(userRoleVo.getRoleIds()).forEach(item->{  // 添加到权限表
                userRole.setRoleId(item);
                userRole.setUserId(userRoleVo.getId());
                userRoleMapper.insertSelective(userRole);
            });
        }
        return ServerResponse.resResponse();
    }


    /**
     * 用户自己更改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    public ServerResponse updatePassword(Integer id,String oldPassword,String newPassword){
        oldPassword=MD5Util.MD5Encode(oldPassword);
        Users users=usersMapper.selectByIdAndPassword(id,oldPassword);
        if(users==null){
            return ServerResponse.resResponse("",-2,"旧密码错误");             // 旧密码错误
        }

        newPassword=MD5Util.MD5Encode(newPassword);
        users.setPassword(newPassword);

        if(usersMapper.updateByPrimaryKeySelective(users)<1){
            return ServerResponse.resResponse("",-2,"系统异常，修改密码失败");  // 系统异常，修改密码失败
        }
        return  ServerResponse.resResponse();
    }

    /**
     * 重置用户密码
     * @param id
     * @param newPassword
     * @return
     */
    public ServerResponse resetUserPassword(Integer id,String newPassword){
        if(newPassword==null){
            return ServerResponse.resResponse("",-2,"密码不能为空");           // 系统异常，重置密码失败
        }
        newPassword=MD5Util.MD5Encode(newPassword);
        users.setId(id);
        users.setPassword(newPassword);
        if(usersMapper.updateByPrimaryKeySelective(users)<1){
            return ServerResponse.resResponse("",-2,"系统异常，重置密码失败");  // 系统异常，重置密码失败
        }
        return  ServerResponse.resResponse();
    }


}
